<template>
  <view class="recommend-container">
    <!-- 顶部搜索区域 -->
    <CustomHeader ref="customHeader"></CustomHeader>
    <view class="top-box">
      <!-- 搜索栏 -->
      <view class="search-bar">
        <view class="search-wrapper">
          <view class="search-input-section">
            <view class="job_type_selector" @click="goToJobTypeSelect">
              <text class="job_type_selector_text">{{
                jobTypeSelectorText || "不限职类"
              }}</text>
              <image
                src="/static/icons/candidate/selector.png"
                class="selector_icon"
              >
              </image>
            </view>
            <view class="split-line">
              <text class="split-text">|</text>
            </view>
            <view class="search-input-wrapper">
              <input
                type="text"
                v-model="searchKeyword"
                placeholder="候选人 | 优势 | 资格证书 | 技能"
                placeholder-class="placeholder"
                class="search-input"
                @input="onSearchInput"
                @confirm="doSearch"
              />
            </view>
          </view>
        </view>

        <view class="search-btn" @click="doSearch">
          <text class="search-btn-text">搜索</text>
        </view>
      </view>

      <!-- 筛选条件 -->
      <view class="filter-section">
        <view class="filter-left">
          <text class="filter-text">综合</text>
        </view>
        <view class="filter-right" @click="showFilter">
          <text class="filter-text">筛选</text>
          <image
            src="/static/icons/hr/option-down-icon.png"
            class="filter-arrow"
          ></image>
        </view>
      </view>
    </view>

    <!-- 候选人列表 -->
    <scroll-view class="talent-list" scroll-y @scrolltolower="loadMore">
      <view
        class="talent-card"
        v-for="(talent, index) in talentList"
        :key="index"
        @click="viewResumeDetail(talent)"
      >
        <view class="talent-header">
          <image
            class="avatar"
            :src="talent.face || '/static/images/avatar.png'"
          />
          <view class="basic-info">
            <view class="name-section">
              <text class="name">{{ talent.realName }}</text>
              <text class="status">{{ talent.status }}</text>
            </view>
            <view class="edu-info">
              <text class="education">{{ talent.highestEduLevel }}</text>
              <text class="school">{{ talent.highestEduSchool }}</text>
              <text class="major">{{ talent.highestEduMajor }}</text>
            </view>
          </view>
          <view class="salary">{{ talent.expectBeginSalary }}-{{ talent.expectEndSalary }}K</view>
        </view>

        <!-- 个人优势 -->
        <view class="advantage-section" v-if="talent.advantage">
          <text class="advantage-text">{{ getDisplayAdvantage(talent.advantage) }}</text>
        </view>

        <!-- 技能标签 -->
        <view class="talent-tags" v-if="talent.skills">
          <text
            class="tag"
            v-for="(skill, skillIndex) in getSkillTags(talent.skills)"
            :key="skillIndex"
            >{{ skill }}</text
          >
        </view>

        <!-- 证书标签 -->
        <view class="credentials-tags" v-if="talent.credentials">
          <text
            class="credential-tag"
            v-for="(credential, credIndex) in getCredentialTags(talent.credentials)"
            :key="credIndex"
            >{{ credential }}</text
          >
        </view>

        <view class="talent-footer">
          <view class="work-info">
            <text class="expect-job">期望：{{ talent.expectJobName }}</text>
            <text class="latest-work" v-if="talent.latestCompany">
              {{ talent.latestCompany }} · {{ talent.latestPosition }}
            </text>
          </view>
          <button class="chat-btn" @tap.stop="startChat(talent)">立即沟通</button>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="hasSearched && talentList.length === 0">
        <text class="empty-text">暂无匹配的候选人</text>
        <text class="empty-tip">尝试调整搜索条件或筛选条件</text>
      </view>

      <uni-load-more 
        :status="loadingStatus" 
        :content-text="{
          contentdown: '上拉显示更多',
          contentrefresh: '正在加载...',
          contentnomore: '没有更多候选人了~尝试减少或者改变要求试试呢~'
        }"
        style="margin-bottom: 40rpx;"
      />
      


    </scroll-view>

    <CustomTabBar :currentIndex="0" />
  </view>
</template>

<script>
import CustomTabBar from "@/components/CustomTabBar.vue";
import CustomHeader from "@/components/CustomHeader.vue";
import { searchResumeApi } from "@/api/company.js";
import { createChatSessionApi } from "@/api/chat.js";

export default {
  components: {
    CustomTabBar,
    CustomHeader,
  },
  data() {
    return {
      searchKeyword: "",
      talentList: [],
      loadingStatus: "more",
      jobTypeSelectorText: "", // 用于显示选中的职位类别
      selectedJobType: null, // 选中的职位类别对象
      searchParams: {
        pageNo: 1,
        pageSize: 10,
        basicTitle: "",
        jobName: "",
        beginAge: "",
        endAge: "",
        sex: "",
        activeTime: "",
        workExpYears: "",
        edu: "",
        beginSalary: "",
        endSalary: "",
        jobStatus: ""
      },
      totalPages: 0,
      isLoading: false,
      hasSearched: false, // 是否已经搜索过
      isFirstLoad: true // 是否首次加载
    };
  },
  methods: {
    // 搜索简历
    async searchResumes(isLoadMore = false) {
      if (this.isLoading) return;
      
      this.isLoading = true;
      
      try {
        if (!isLoadMore) {
          this.searchParams.pageNo = 1;
          this.talentList = [];
          this.loadingStatus = "loading";
        }
        
        // 构建搜索参数
        const params = {
          ...this.searchParams,
          basicTitle: this.searchKeyword,
          jobName: this.selectedJobType?.name || ""
        };
        
        const response = await searchResumeApi(params);
        
        if (response && response.list !== undefined) {
          if (isLoadMore) {
            this.talentList = [...this.talentList, ...response.list];
          } else {
            this.talentList = response.list;
          }
          
          this.totalPages = response.totalPages || 0;
          this.hasSearched = true;
          
          // 更新加载状态
          if (this.searchParams.pageNo >= this.totalPages) {
            this.loadingStatus = "noMore";
          } else if (response.list.length === 0) {
            // 如果返回数据为空，也认为没有更多数据
            this.loadingStatus = "noMore";
          } else {
            this.loadingStatus = "more";
          }
        } else {
          // 如果没有返回数据，设置为没有更多
          this.loadingStatus = "noMore";
        }
      } catch (error) {
        console.error("搜索失败:", error);
        uni.showToast({
          title: "搜索失败，请重试",
          icon: "none"
        });
        this.loadingStatus = "more";
      }
      
      this.isLoading = false;
    },
    
    showFilter() {
      // 跳转到筛选页面
      uni.navigateTo({
        url: "/pages/company/recommend/filter",
      });
    },
    
    goToJobTypeSelect() {
      console.log("跳转到职位类别选择页面");
      // 跳转到职位类别选择页面
      uni.navigateTo({
        url: "/pages/common/jobTypeSelector",
      });
    },
    
    async startChat(talent) {
      try {
        // 创建会话
        console.log('创建聊天会话...');
        const sessionData = await createChatSessionApi(talent.userId);
        console.log('会话创建成功:', sessionData);
        
        // 将会话添加到本地存储
        const { useSessionStore } = await import('@/stores/modules/session');
        const sessionStore = useSessionStore();
        sessionStore.upsertSession(sessionData);
        
        // 跳转到聊天页面
        uni.navigateTo({
          url: `/pages/company/chat?sessionId=${sessionData.id}&name=${encodeURIComponent(talent.realName || '候选人')}&candidateId=${talent.userId}`
        });
      } catch (error) {
        console.error('创建会话失败:', error);
        uni.showToast({
          title: '进入聊天失败',
          icon: 'none'
        });
      }
    },
    
    viewResumeDetail(talent) {
      // 查看简历详情
      uni.navigateTo({
        url: `/pages/candidate/resume/watchCandidateResume?userId=${talent.userId}&resumeExpId=${talent.resumeExpId}`,
      });
    },
    
    async loadMore() {
      if (this.loadingStatus === "noMore" || this.isLoading) return;
      
      this.searchParams.pageNo++;
      await this.searchResumes(true);
    },
    
    onSearchInput(e) {
      this.searchKeyword = e.detail.value;
    },
    
    doSearch() {
      // 保存搜索关键词到搜索参数
      this.searchParams.basicTitle = this.searchKeyword;
      
      // 保存筛选条件到本地存储
      this.saveFiltersToLocal();
      
      this.searchResumes();
    },
    
    // 处理个人优势显示（限制字数）
    getDisplayAdvantage(advantage) {
      if (!advantage) return "";
      
      // 移除HTML标签和换行符
      const plainText = advantage.replace(/<[^>]*>/g, "").replace(/\n/g, " ");
      
      // 限制显示字数
      if (plainText.length > 50) {
        return plainText.substring(0, 50) + "...";
      }
      
      return plainText;
    },
    
    // 处理技能标签
    getSkillTags(skills) {
      if (!skills) return [];
      
      const skillArray = skills.split(',').filter(item => item.trim());
      // 最多显示5个技能
      return skillArray.slice(0, 5);
    },
    
    // 处理证书标签
    getCredentialTags(credentials) {
      if (!credentials) return [];
      
      const credentialArray = credentials.split(',').filter(item => item.trim());
      // 最多显示3个证书
      return credentialArray.slice(0, 3);
    },
    handleFilterData(filterData) {
      // 处理筛选数据的逻辑
      console.log("处理筛选数据:", filterData);
      
      // 更新搜索参数
      Object.assign(this.searchParams, filterData);
      
      // 保存筛选条件到本地存储
      this.saveFiltersToLocal();
      
      // 重新搜索
      this.searchResumes();
    },
    
    // 保存筛选条件到本地存储
    saveFiltersToLocal() {
      try {
        // 确保搜索关键词同步到搜索参数
        this.searchParams.basicTitle = this.searchKeyword;
        
        const filtersToSave = {
          selectedJobType: this.selectedJobType,
          jobTypeSelectorText: this.jobTypeSelectorText,
          searchParams: { ...this.searchParams },
          searchKeyword: this.searchKeyword
        };
        
        uni.setStorageSync("resumeSearchFilters", filtersToSave);
      } catch (error) {
        console.error("保存筛选条件失败:", error);
      }
    },
    
    // 从本地存储读取筛选条件
    loadFiltersFromLocal() {
      try {
        const savedFilters = uni.getStorageSync("resumeSearchFilters");
        
        if (savedFilters) {
          
          // 恢复职位类型选择
          if (savedFilters.selectedJobType) {
            this.selectedJobType = savedFilters.selectedJobType;
            this.jobTypeSelectorText = savedFilters.jobTypeSelectorText || "";
          }
          
          // 恢复搜索参数
          if (savedFilters.searchParams) {
            Object.assign(this.searchParams, savedFilters.searchParams);
          }
          
          // 恢复搜索关键词到输入框
          if (savedFilters.searchKeyword) {
            this.searchKeyword = savedFilters.searchKeyword;
          } else if (savedFilters.searchParams && savedFilters.searchParams.basicTitle) {
            this.searchKeyword = savedFilters.searchParams.basicTitle;
          }
          
          return true; // 表示有保存的筛选条件
        }
        
        return false; // 表示没有保存的筛选条件
      } catch (error) {
        console.error("读取筛选条件失败:", error);
        return false;
      }
    },
    
    // 重置筛选条件
    resetFilters() {
      // 重置数据
      this.selectedJobType = null;
      this.jobTypeSelectorText = "";
      this.searchKeyword = "";
      this.searchParams = {
        pageNo: 1,
        pageSize: 10,
        basicTitle: "",
        jobName: "",
        beginAge: "",
        endAge: "",
        sex: "",
        activeTime: "",
        workExpYears: "",
        edu: "",
        beginSalary: "",
        endSalary: "",
        jobStatus: ""
      };
      
      // 清除本地存储
      try {
        uni.removeStorageSync("resumeSearchFilters");
      } catch (error) {
        console.error("清除本地筛选条件失败:", error);
      }
    },
  },
  // 页面加载时的处理
  mounted() {
    // 监听职位类别选择事件
    uni.$on("updateJobType", (data) => {
      if (!data) {
        this.selectedJobType = null;
        this.jobTypeSelectorText = "";
      } else {
        this.selectedJobType = data;
        this.jobTypeSelectorText = data.name;
      }
      
      // 保存筛选条件到本地存储
      this.saveFiltersToLocal();
    });

    // 监听筛选确认事件
    uni.$on("filterConfirm", (filterData) => {
      // 这里可以根据筛选数据更新候选人列表
      this.handleFilterData(filterData);
    });

    // 初始化加载筛选条件和数据
    this.loadFiltersFromLocal();
    
    // 页面加载时自动搜索
    this.searchResumes();
  },
  // 页面卸载时清理事件监听
  beforeDestroy() {
    uni.$off("updateJobType");
    uni.$off("filterConfirm");
  },
  // 页面生命周期方法
  onShow() {
    // 如果是首次加载，跳过（mounted中已经处理）
    if (this.isFirstLoad) {
      this.isFirstLoad = false;
      return;
    }
    
    // 从本地存储读取筛选条件
    this.loadFiltersFromLocal();
    
    // 自动执行搜索
    this.searchResumes();
  }
};
</script>

<style lang="scss">
.recommend-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.top-box {
  background-color: #ffffff;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

/* 搜索栏 */
.search-bar {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.search-wrapper {
  flex: 1;
  height: 80rpx;
  background-color: #f8f8f8;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}

.search-input-section {
  flex: 1;
  display: flex;
  align-items: center;
  height: 100%;
}

.search-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15rpx;
  cursor: pointer;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
}

.split-line {
  padding: 0 10rpx;
}

.split-text {
  color: #d0d0d0;
  font-size: 28rpx;
}

.search-input-wrapper {
  flex: 1;
  padding-right: 20rpx;
}

.search-input {
  width: 100%;
  font-size: 24rpx;
  color: #333333;
}

.placeholder {
  color: #b0b0b0;
}

.search-btn {
  width: 110rpx;
  height: 75rpx;
  background-color: #00bdb4;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-btn-text {
  color: #ffffff;
  font-size: 28rpx;
  font-weight: 500;
}

/* 筛选条件 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.filter-left,
.filter-right {
  display: flex;
  align-items: center;
}

.filter-text {
  font-size: 28rpx;
  color: #333333;
}

.filter-right {
  cursor: pointer;
}

.filter-arrow {
  width: 24rpx;
  height: 24rpx;
  margin-left: 8rpx;
}

.talent-list {
  height: calc(100vh - 280rpx);
  padding-bottom: 100rpx; /* 为底部TabBar留出空间 */
}

.talent-card {
  background: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.talent-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin-right: 20rpx;
  }

  .basic-info {
    flex: 1;

    .name-section {
      display: flex;
      align-items: center;
      margin-bottom: 8rpx;

      .name {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-right: 12rpx;
      }

      .status {
        font-size: 20rpx;
        color: #00bdb4;
        background-color: #e8f7f7;
        padding: 4rpx 8rpx;
        border-radius: 4rpx;
      }
    }

    .edu-info {
      display: flex;
      align-items: center;
      margin-top: 8rpx;
      
      .education {
        font-size: 26rpx;
        color: #666;
        margin-right: 8rpx;
      }
      
      .school {
        font-size: 26rpx;
        color: #666;
        margin-right: 8rpx;
      }
      
      .major {
        font-size: 26rpx;
        color: #999;
      }
    }
  }

  .salary {
    font-size: 32rpx;
    color: #00bdb4;
    font-weight: bold;
  }
}

/* 个人优势 */
.advantage-section {
  margin-bottom: 15rpx;
  
  .advantage-text {
    font-size: 26rpx;
    color: #666;
    line-height: 1.4;
  }
}

/* 技能标签 */
.talent-tags {
  margin-bottom: 15rpx;

  .tag {
    display: inline-block;
    background: #e8f4ff;
    color: #1890ff;
    padding: 6rpx 12rpx;
    margin-right: 12rpx;
    margin-bottom: 8rpx;
    border-radius: 4rpx;
    font-size: 22rpx;
  }
}

/* 证书标签 */
.credentials-tags {
  margin-bottom: 15rpx;
  
  .credential-tag {
    display: inline-block;
    background: #fff7e6;
    color: #fa8c16;
    padding: 6rpx 12rpx;
    margin-right: 12rpx;
    margin-bottom: 8rpx;
    border-radius: 4rpx;
    font-size: 22rpx;
  }
}

.talent-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 15rpx;

  .work-info {
    flex: 1;
    
    .expect-job {
      display: block;
      font-size: 26rpx;
      color: #333;
      margin-bottom: 4rpx;
    }
    
    .latest-work {
      display: block;
      font-size: 24rpx;
      color: #999;
    }
  }

  .chat-btn {
    background: #007aff;
    color: #fff;
    font-size: 26rpx;
    padding: 10rpx 30rpx;
    border-radius: 30rpx;
    line-height: 1;
    border: none;
  }
}

.filter-arrow {
  width: 24rpx;
  height: 24rpx;
  margin-left: 8rpx;
}

.job_type_selector {
  display: flex;
  align-items: center;
  padding: 10rpx;
  background-color: #f0fefe;
  border-radius: 30rpx;
}
.job_type_selector_text {
  font-size: 23rpx;
  color: #00bdb4;
}
.selector_icon {
  width: 34rpx;
  height: 34rpx;
  margin-left: 5rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 40rpx;
  
  .empty-text {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .empty-tip {
    font-size: 26rpx;
    color: #999;
    text-align: center;
  }
}


</style>